<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>three.js examples</title>
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <script src="js/jquery-3.5.1.min.js"></script>
    <script src="js/lhgdialog/lhgcore.lhgdialog.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/TweenMax.min.js"></script>
</head>
<style>
.dd a{ color: #fff; }
</style>
<body style="margin: 0">

<div class="Mbox"></div>

<div style="position: absolute;top: 0px; left: 0px" id="stat"></div>
<div class="dd" style="position: absolute;bottom: 0px;color: #fff ;background: #000; left: 0px;width: 200px;height: 200px;border:1px solid red">
    <a href="javascript:void(0)" id="reserCamera1">添加摄像头</a>&nbsp;&nbsp;&nbsp;
    <a href="javascript:void(0)" id="reserCamera0">取消添加摄像头</a>
    <br>
    <a href="javascript:void(0)" id="doMen1">添加工人</a>&nbsp;&nbsp;&nbsp;
    <a href="javascript:void(0)" id="doMen0">取消添加人</a>
    <br>
    <a href="javascript:void(0)" id="xinbiaoMM1">添加信标</a>&nbsp;&nbsp;&nbsp;
    <a href="javascript:void(0)" id="xinbiaoMM0">取消添加信标</a>
    <br>
    <a href="javascript:void(0)" id="cancelcamera">清理所有摄像头</a>
    <br>
    <a href="javascript:void(0)" id="cancelmen">清理所有工人</a>
    <br>

    <a href="javascript:void(0)" id="cancelxinbiao">清理所有信标</a>


</div>
<!--<div style="position: absolute; color: #d9edf7  ; top: 120px;">-->
<!--    选中着色器-->
<!--    <div class="color" style="background:#AA4631 " ></div>-->
<!--    <div class="color" style="background:#130AF2 " ></div>-->
<!--    <div class="color" style="background:#C5B49A " ></div>-->
<!--    <div class="color" style="background:#6A5ACD " ></div>-->
<!--    <div class="color" style="background:#E8C279 " ></div>-->
<!--</div>-->


<script type="x-shader/x-vertex" id="vertexshader">

			uniform float amplitude;

			attribute vec3 displacement;
			attribute vec3 customColor;

			varying vec3 vColor;

			void main() {

				vec3 newPosition = position + amplitude * displacement;

				vColor = customColor;

				gl_Position = projectionMatrix * modelViewMatrix * vec4( newPosition, 1.0 );

			}

		</script>

<script type="x-shader/x-fragment" id="fragmentshader">

			uniform vec3 color;
			uniform float opacity;

			varying vec3 vColor;

			void main() {

				gl_FragColor = vec4( vColor * color, opacity );

			}

		</script>
<style>
    .color{
        background: #130AF2;
        width: 30px;
        height: 30px;
        border-radius: 4px;
        margin: 10px;
    }
</style>

<script language="JavaScript">
    // 参数接收
    function GetArgsFromHref(keys='')
    {
        let urlinfo=window.location.href; //获取当前页面的url
        let len=urlinfo.length;//获取url的长度
        let offset=urlinfo.indexOf("?");//设置参数字符串开始的位置
        let newsidinfo=urlinfo.substr(offset+1,len)//取出参数字符串 这里会获得类似“id=1”这样的字符串
        let newsids=newsidinfo.split("&");//对获得的参数字符串按照“=”进行分割


        let newArr = {}
        let kv = ''
        for(let i=0;i<newsids.length;i++){
            kv = newsids[i].split("=")
            newArr[kv[0]]=kv[1]

        }
        if(keys && newArr[keys] ){
            return newArr[keys]
        }else{
            return  ""
        }

    }
    // 文件目录  lot&filename=LOT9-a-土建.gltf
    let gltfpath = GetArgsFromHref("path") ? "./gltf/"+GetArgsFromHref("path")+"/":"./gltf/lot/"
    let gltfurl =decodeURI(GetArgsFromHref("filename"))
    gltfurl=gltfurl?gltfurl:"LOT9-a-土建.gltf"

    //console.log(3333333333)
    //console.log(gltfurl)
</script>

<script type="module">
    // 加载主要js

    import * as THREE from './build/three.module.js';
    // 加载内存仪表盘
    import Stats from './threejs/jsm/libs/stats.module.js';
    // 制作一个地板
    let textMesh2,textMesh
    import { MapControls } from './threejs/jsm/controls/OrbitControls.js';
    import {
        PlaneGeometry,
        MeshPhongMaterial,
        Mesh
    } from './build/three.module.js';
    import { OrbitControls } from './threejs/jsm/controls/OrbitControls.js';
    import { GLTFLoader } from './threejs/jsm/loaders/GLTFLoader.js';
    import { EffectComposer } from './threejs/jsm/postprocessing/EffectComposer.js';
    import { RenderPass  } from './threejs/jsm/postprocessing/RenderPass.js';
    import { OutlinePass  } from './threejs/jsm/postprocessing/OutlinePass.js';
    //说色工具  发光体
    import { ToonShader1, ToonShader2, ToonShaderHatching, ToonShaderDotted } from './threejs/jsm/shaders/ToonShader.js';
    import { TWEEN } from './threejs/jsm/libs/tween.module.min.js';
    // 动态仪表盘
    import { GUI } from './threejs/jsm/libs/dat.gui.module.js';

    import {
        DirectionalLight,
        PMREMGenerator,
        DirectionalLightHelper,
        HemisphereLight,
        HemisphereLightHelper
    } from './build/three.module.js';
    import { CSS2DRenderer, CSS2DObject } from './threejs/jsm/renderers/CSS2DRenderer.js';
    import { CSS3DRenderer, CSS3DObject } from './threejs/jsm/renderers/CSS3DRenderer.js';
    let  newjsondata = {}
    let jsondata= {}
    let isphone =false
        let centetposition;
    let modelSize
    let firstCont;
    let firstContpostion
    if(GetArgsFromHref("json")){
        $.ajaxSettings.async = false;

        $.getJSON(gltfpath+GetArgsFromHref("json")+".json",function(jsonObj){
            jsondata = jsonObj
            //console.log(gltfpath+GetArgsFromHref("json")+".json")

            for(let i in jsondata ){
                //console.log(jsondata[i].Level)

                if(!newjsondata[jsondata[i].Level]){
                    newjsondata[jsondata[i].Level]=[]
                }
                newjsondata[jsondata[i].Level].push(jsondata[i].UId)
            }

        })
        console.log("jsonnnnnnnnnnnnnnnnnnnnnnnnn")
        console.log(newjsondata)
        console.log(jsondata)
    }

    let pmremGenerator;
    // 当前选中颜色index
    let colorIndex =0

    // 模型的三维坐标
    let modelBox
    // 模型的 长宽高  暂时用  x y z 表示
    let modelX ,modelY,modelZ;
    // 颜色数组
    let colorArr =["#AA4631","#130AF2","#C5B49A","#6A5ACD","#E8C279"]
    //点击部件时候 存储旧样式  方便还原
    let oldSelect,oldMaterial;
    // 摄像机 位置
    let cameraPosition={x:100,y:100,z:100}

    let
        // 摄像头
        camera,
        // 场景
        scene,
        // 仪表盘
        gui,
        // 渲染器
        renderer,
        // 地板
        floor,
        // 灯光
        directionalLight,
        // 构件对象
        gltfobj,
        gltfobj2,
        // 摄像旋转控制
        controls,
        // 内存显示器
        stats,
        outlinePass,
        curefont,
        // 特殊效果
        composerAll;



    $(function(){
        // 初始化
         init();
        //doinitLight()
        scene.background = new THREE.Color( "#83AF9B" );
        // 灯光
        dolight()
        // dodiban()
        // 渲染
        // doAxsHelper()
        addAxesHelper()
        //console.log("当前摄像头位置")
        //console.log(camera.position)
        //console.log("当前场景位置")
        //console.log(scene.position)




    })

    let  docameraAdd =false
    let  addMenAdd =false
    let  xinbiaoAdd =false
    function reserCamera(type){
        if(type==1){
            docameraAdd=true
            addMenAdd=false
            xinbiaoAdd=false
        }else{
            docameraAdd=false
            addMenAdd=false
            xinbiaoAdd=false
        }
        camera.lookAt(firstCont)
        camera.updateProjectionMatrix();
        // camera.position.copy(firstContpostion)
        // render()
    }

    function xinbiaoMM(type){
        if(type==1){
            xinbiaoAdd=true
            docameraAdd=false
            addMenAdd=false
        }else{
            xinbiaoAdd=false
            docameraAdd=false
            addMenAdd=false
        }
        camera.lookAt(firstCont)
        camera.updateProjectionMatrix();
        // camera.position.copy(firstContpostion)
        // render()
    }

    function doMen(type){
        if(type==1){
            addMenAdd=true
            docameraAdd=false
            xinbiaoAdd=false
        }else{
            docameraAdd=false
            addMenAdd=false
            xinbiaoAdd=false
        }
        console.log(firstCont)
        console.log(firstContpostion)
        camera.lookAt(firstCont)
        camera.updateProjectionMatrix();
        // camera.position.copy(firstContpostion)
        // render()
    }




    let planeGroup =[]
    let labelRenderer

     let  cando  =false

    function createText(obj,location){


        const earthDiv = document.createElement( 'div' );
        earthDiv.className = 'label';
        earthDiv.textContent = "第三方金黃色的積分換";
        earthDiv.style.marginTop = '';
        earthDiv.style.fontSize = '2em';
        earthDiv.style.background = '#ffffff';
        earthDiv.style.color = '#f60';
        const earthLabel = new CSS3DObject( earthDiv );
        earthLabel.position.copy(location );
        earthLabel.position.x+=0.1

        const geometryx = new THREE.BoxBufferGeometry(40000, 40000, 40000 );
        const materialx = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
        const meshx = new THREE.Mesh( geometryx, materialx );
        meshx.position .copy(location);
        meshx.position.x+=0.1
        meshx.add(earthLabel)


        cando=true

        scene.add(meshx)
        //console.log("2222222xxxxxxxxxx")
        //console.log(location)
        labelRenderer.render( scene, camera );
        //console.log("22222222xxxxxxxxxx")
        controls.addEventListener( 'change', changexxx ); // use if there is no animation loop
        return
        const loader = new THREE.FontLoader();
        loader.load( 'threejs/fonts/siyuans.json', function ( font ) {
            curefont = font
            //console.log("curefont")
            //console.log(modelSize/20)
            const textGeo = new THREE.TextBufferGeometry(codeText, {
                font: curefont,
                size: modelSize/20,
                height: 122,
                curveSegments:122

            } );
            const textMaterial = new THREE.MeshBasicMaterial( { color: 0x000000} );
            textMesh = new THREE.Mesh(textGeo,textMaterial);
            textMesh.position.copy(location );
            textMesh.position.x+=0.1
            textMesh.rotation.copy(camera.rotation)
            textGroup.push(textMesh)
            scene.add( textMesh );
           let url = changeCanvas()


            //console.log("333333333333333333311111111111")
            //console.log(codeText.length*modelSize/20)
            //console.log(modelSize/20)
            let geometry1 = new THREE.PlaneGeometry(codeText.length*modelSize/20, modelSize/20)
            let texture = THREE.ImageUtils.loadTexture(url, null, function (t) {})

            let material1 = new THREE.MeshBasicMaterial({
                map: texture,
                side: THREE.DoubleSide,
                opacity: 1,
                transparent: true,
            })

            let rect = new THREE.Mesh(geometry1, material1)
            rect.position.copy(location );
            rect.position.x+=0.1
            rect.rotation.copy(camera.rotation)
            scene.add(rect)
            planeGroup.push(rect)

          //
          //
          //   var material = new THREE.MeshBasicMaterial({
          //       map: texture
          //   });
          // let   geometry = new THREE.PlaneGeometry(codeText.length * modelSize/20,  modelSize/20,codeText.length *   modelSize/20);
          //   geometry.faces[0].color.set(0xffffff)
          //   //console.log(geometry.position)
          // let   mesh = new THREE.Mesh(geometry, material);
          //   mesh.position.copy(location)
          //   mesh.position.x+=0.1
          //   mesh.rotation.copy(camera.rotation)
          //   scene.add(mesh);


            controls.update()


        } );


    }
    var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d');

    function changeCanvas() {
        canvas.width = 25308
        canvas.height = 2812
        //制作矩形
        ctx.fillStyle = "rgba(255,165,0,1)";
        ctx.fillRect(0, 0,  canvas.width , canvas.height)
        ctx.fillStyle = "#000000";
        ctx.font = 'normal '+canvas.width/20+'pt "楷体"'
        ctx.fillText('模型介绍', 100, 20)
        let textWord = '该模型由小少小同学制作完成'
        //文字换行
        let len = parseInt(textWord.length / 10)
        for (let i = 0; i < (len + 1); i++) {
            let space = 10
            if (i === len) {
                space = textWord.length - len * 10
            }
            //console.log('len+' + len, 'space+' + space)
            let word = textWord.substr(i * 10, space)
            ctx.fillText(word, canvas.width/50, canvas.width/50*(i+1))
        }
        return  canvas.toDataURL('image/png');
    }




    // 染色切换
    $(function(){





        $(".color").click(function(){

            colorIndex=$(this).index()
        })

    })
    // // 初始化灯光
    // function doinitLight() {
    // 	var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.3 );//模拟远处类似太阳的光源
    // 	directionalLight.color.setHSL( 0.1, 1, 0.95 );
    // 	directionalLight.position.set( 0, 200, 0).normalize();
    // 	scene.add( directionalLight );
    //
    // 	var ambient = new THREE.AmbientLight( 0x404040 ); //AmbientLight,影响整个场景的光源
    // 	ambient.position.set(30,30,30);
    // 	scene.add( ambient );
    // }




    let shadowCameraHelper
    // 灯光
    function dolight(){

        // 环境光线
        const ambientLight = new THREE.AmbientLight( 0xffffff,1);
        ambientLight.position.copy(camera.position);
        scene.add( ambientLight );
        let hemisphereLight = new HemisphereLight(0xffffff, 0xffffff,1);
        hemisphereLight.position.copy(camera.position);
        scene.add(hemisphereLight);
        // // 模拟太阳光线
        const directionalLight = new THREE.DirectionalLight( 0xffffff, 1 );
         directionalLight.position.copy(camera.position);
        //
         scene.add(directionalLight)
        //
        //
        //
        // directionalLight.position.copy(camera.position);
        // scene.add( directionalLight );
        //  let hemisphereLight = new HemisphereLight(0xffffff, 0xffffff, 1);
        // // hemisphereLight.position.set(0, 8, 0);
        // hemisphereLight.position.copy(camera.position);
        // // scene.add(directionalLight);
        //  scene.add(hemisphereLight);

        return

        //
        //
        // // 平行光  模拟太阳光
        // directionalLight = new DirectionalLight(0xffffff, 0.5);
        // directionalLight.position.set(camera.position.x, camera.position.x,camera.position.z);
        // let dhelper = new DirectionalLightHelper(directionalLight, 5, 0xff0000);
        // // 光源直接放置于场景之上，光照颜色从天空光线颜色颜色渐变到地面光线颜色。
        // let hemisphereLight = new HemisphereLight(0xffffff, 0xffffff, 0.4);
        // hemisphereLight.position.set(0, 8, 0);
        //
        // scene.add(directionalLight);
        // scene.add(hemisphereLight);
        // // 光源开启阴影
        // directionalLight.castShadow = true;
        // directionalLight.shadow.mapSize = new THREE.Vector3(1024, 1024,1024);

    }

    // 坐标轴xyz  辅助器
    function doAxsHelper(){
        return
        let axs  = new THREE.AxesHelper(modelSize/10)
        // axs.position.x-=10000
        axs.position.copy(centetposition)



        let geometryx = new THREE.BoxGeometry(modelSize/10,modelSize/10, modelSize/10); //宽，高，深
         let material = new THREE.MeshBasicMaterial({
             color: "#f60",
             wireframe: true
         }); //wireframe默认为false

        var cube=new THREE.Mesh(geometryx,material);
//scene.add(cube);
        var axesHelper = new THREE.AxesHelper( 5 );
//scene.add( axesHelper );

        var objectTotal = new THREE.Group();
        objectTotal.add(cube);
        objectTotal.add(axesHelper);
        scene.add(objectTotal);

        let sc2 = new THREE.Scene()

        $(".dd").append(objectTotal)
         // scene.add(axs)
    }
    let texturexx=new THREE.TextureLoader();
    let cubeTexture=texturexx.load("./textures/camera/camera.png");
    let xinbiaoText=texturexx.load("./textures/xinhao/xinbiao.gif");


    let cubeTextureMen=texturexx.load("./textures/men/g.png");

    // 初始化实力
    function init() {

        doloadFlag()
        $("#reserCamera1").click(function(){
            reserCamera(1)
        })

        $("#reserCamera0").click(function(){
            reserCamera(0)
        })


        $("#doMen0").click(function(){
            doMen(0)
        })


        $("#doMen1").click(function(){
            doMen(1)
        })


        $("#showscene").click(function(){
            console.log(scene)
            console.log(scene.children)
            // for(let i in scene){
            //
            //     console.log(i)
            // }
        })

        $("#xinbiaoMM0").click(function(){
            xinbiaoMM(0)
        })

        $("#xinbiaoMM1").click(function(){
            xinbiaoMM(1)
        })



        $("#cancelcamera").click(function(){
            let newa = []

            for(let z in cameragroup){
                newa.push(cameragroup[z].uuid)
            }

            for(let i in scene.children){
                if(scene.children[i].isMesh){
                    console.log(scene.children[i])
                    console.log(newa)
                    if(newa.indexOf(scene.children[i].uuid)!=-1){
                        // scene.children[i].visible=false
                        scene.children[i].visible=false
                        // scene.remove(scene.children[i])
                    }
                    // console.log(scene.children[i])
                    // scene.children[i].remove(scene.children[i])
                    // scene.children[i].material.visible=false
                    // mengroup[i].visible=false
                }
            }
            render()
        })


        $("#cancelxinbiao").click(function(){

            let newa = []

            for(let z in xinbiaoGroup){
                newa.push(xinbiaoGroup[z].uuid)
            }
            console.log(scene.children)

            for(let i in scene.children){
                if(scene.children[i].isGroup){

                    if(scene.children[i].userData.typex=="flag"){

                        scene.children[i].visible=false
                    }

                    //

                    if(newa.indexOf(scene.children[i].uuid)!=-1){

                    }
                    // console.log(scene.children[i])
                    // scene.children[i].remove(scene.children[i])
                    // scene.children[i].material.visible=false
                    // mengroup[i].visible=false

                }

            }

            console.log(xinbiaoGroup)
            render()
        })

        $("#cancelmen").click(function(){
            let newa = []

            for(let z in mengroup){
                newa.push(mengroup[z].uuid)
            }
            for(let i in scene.children){
                if(scene.children[i].isMesh){
                   console.log(scene.children[i])
                   console.log(newa)
                    if(newa.indexOf(scene.children[i].uuid)!=-1){
                        scene.children[i].visible=false
                    }
                    // console.log(scene.children[i])
                    // scene.children[i].remove(scene.children[i])
                    // scene.children[i].material.visible=false
                    // mengroup[i].visible=false

                }

            }

            console.log(mengroup)
            render()
        })



        dostats()

        const container = $(".Mbox");
     //   document.body.appendChild( container );

        // 3D标注必须
        labelRenderer = new CSS3DRenderer();
        labelRenderer.setSize( window.innerWidth, window.innerHeight );
        labelRenderer.domElement.style.position = 'absolute';
        labelRenderer.domElement.style.top = '0px';
        container.append( labelRenderer.domElement );



        camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1,1000 );
        camera.position.set( -10, 8, 20);


        scene = new THREE.Scene();
        // scene.background=new THREE.Color("#cccccc")
        // 渲染器
        doWebGLRenderer()
        setOutLine()
        // 加载gltf模型
        doloadGltfs()

        // if(gltfurl=="lot9a.gltf"){
        //
        //     gltfurl ="lot9a-paishui.gltf"
        //     doloadGltfs()
        //
        //     gltfurl ="lot9a-tuanjian.gltf"
        //     doloadGltfs()
        //
        //
        //
        // }

        //全局部件颜色改为白色
        //     scene.overrideMaterial= new THREE.MeshLambertMaterial({color:0xffffff})

        // 模型Mesh开启阴影
        container.append( renderer.domElement)

       // container.appendChild( );


        doOrbiControls();

        // container.append('<div style="background:red;position:absolute; top:0px; height:100px;width:100px">erwer</div>')

        window.addEventListener( 'resize', onWindowResize, false );

        //
        // // 内存仪表盘
        // dostats()
        // // 创建画布
        // const container = document.createElement( 'div' );
        // document.body.appendChild( container );
        // // 透视摄像机
        // camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1,1000 );
        // camera.position.set(cameraPosition.x,cameraPosition.y,cameraPosition.z);
        // // 场景
        // scene = new THREE.Scene();
        // //全局部件颜色改为白色
        // //     scene.overrideMaterial= new THREE.MeshLambertMaterial({color:0xffffff})
        // let i = 0
        // // scene.background=new THREE.Color( "#353535" );
        // // 加载模型
        // doloadGltfs()
        // // 渲染器
        // doWebGLRenderer()
        // // 模型Mesh开启阴影
        // container.appendChild( renderer.domElement );
        // // 旋转控制
        // doOrbiControls()
        // // 开启页面点击监控

        $(document).click(onDocumentMouseDown)
        // window.addEventListener( 'click', onDocumentMouseDown ); // use if there is no animation loop
        // // 页面缩小重置
        // window.addEventListener( 'resize', onWindowResize, false );

    }


    // 摄像头 旋转操控
    function doOrbiControls(){


        //
        // controls = new MapControls( camera, renderer.domElement );
        //
        // controls.addEventListener( 'change', render ); // call this only in static scenes (i.e., if there is no animation loop)
        //
        // controls.enableDamping = true; // an animation loop is required when either damping or auto-rotation are enabled
        // controls.dampingFactor = 0.05;
        //
        // controls.screenSpacePanning = false;
        //
        // controls.minDistance = 100;
        // controls.maxDistance = 500;
        //
        // controls.maxPolarAngle = Math.PI / 2;
        // controls.update();
        //
        //
        controls = new OrbitControls( camera, labelRenderer.domElement );
        // controls.reset();
        controls.autoRotate = true;//是否自动旋转
        controls.autoRotateSpeed = 0.5;//自动旋转速度，正比
        controls.screenSpacePanning = true;
        controls.addEventListener( 'change', render ); // use if there is no animation loop
        controls.update()

    }

    // 渲染器
    function doWebGLRenderer(){
        renderer = new THREE.WebGLRenderer( { antialias: true } );
        // renderer.setClearColor( 0xcccccc );

        renderer.setPixelRatio( window.devicePixelRatio );
        renderer.setSize( window.innerWidth, window.innerHeight );
        renderer.toneMapping = THREE.ACESFilmicToneMapping;
        renderer.toneMappingExposure = 1;
        renderer.outputEncoding = THREE.sRGBEncoding;

        renderer.physicallyCorrectLights = true;
        renderer.outputEncoding = THREE.sRGBEncoding;

        renderer.sortObjects = false;
        // 首先渲染器开启阴影
        renderer.shadowMap.enabled = true;


        // 环境光影响
        pmremGenerator = new PMREMGenerator(renderer );
        pmremGenerator.compileEquirectangularShader();
    }


    let axesDiv,axesScene,axesCamera,axesRenderer,axesCorner;
   function  addAxesHelper () {
        axesDiv = document.createElement('div');
        document.body.appendChild(axesDiv );
        axesDiv.classList.add('axes');

        const {clientWidth, clientHeight} = axesDiv;

         axesScene = new THREE.Scene();
        axesCamera = new THREE.PerspectiveCamera( 50, clientWidth / clientHeight, 0.1, 10 );
        axesScene.add( axesCamera );

        axesRenderer = new THREE.WebGLRenderer( { alpha: true } );
        axesRenderer.setPixelRatio( window.devicePixelRatio );
        axesRenderer.setSize( axesDiv.clientWidth,axesDiv.clientHeight );

        axesCamera.up =camera.up;
        axesCorner = new THREE.AxesHelper(5);
        axesScene.add( axesCorner );
        axesDiv.appendChild(axesRenderer.domElement);
    }


    // 后处理  选中部件加上外线
    function setOutLine(){
        composerAll = new EffectComposer( renderer );
        const renderPass = new RenderPass( scene, camera );
        composerAll.addPass( renderPass );

        outlinePass = new OutlinePass( new THREE.Vector2( window.innerWidth, window.innerHeight ), scene, camera );


        // edgeStrength: 3.0,  //强度 默认3
        //     edgeGlow: 1,    强度 默认1
        // edgeThickness: 1.0, //边缘浓度
        //     pulsePeriod: 0,  闪烁频率 默认0 值越大频率越低
        // usePatternTexture: false  使用纹理
        // visibleEdgeColor #ffffff 边缘可见部分发光颜色
        // hiddenEdgeColor #190a05  边缘遮挡部分发光颜色

        outlinePass.visibleEdgeColor.set('#f60'); // 选中颜色
        outlinePass.hiddenEdgeColor.set('#f60'); // 选中颜色
        // outlinePass.hiddenEdgeColor.set("#b33535");
        outlinePass.edgeStrength =1;
        outlinePass.edgeGlow =2;
        composerAll.addPass( outlinePass );

    }

    let gltfgroup = []
    let  objectMESH = {}


    let flagObj
    function  doloadFlag(){
        try{
            let i = 0
            // scene.background=new THREE.Color( "#353535" );
            const loader = new GLTFLoader().setPath(gltfpath );
            loader.load( "flag.gltf", function ( gltf ) {
                //console.log(gltf.scene)
                // //console.log(JSON.stringify(gltf.scene))
                // //console.log(gltf)
                gltf.scene.traverse( function ( child ) {
                    if(child.isMesh){
                       // child.material.color.set( 0xff0000 );
                        // child.material.emissive =  child.material.color;
                    }
                } );
                gltf.scene.userData.typex= "flag"
                flagObj=gltf
            } );

        }catch (e) {
            //console.log("异常错误")
            //console.log(e)
            $.dialog({id:'loading'}).close();

        }
    }

    // 加载gltf 模型
   async  function   doloadGltfs(){
        $.dialog({
            id: 'loading',
            title: false,
            cancel: false,
            fixed: true,
            lock: true,
            resize: false,
        })
        try{
            let i = 0
            // scene.background=new THREE.Color( "#353535" );
            const loader = new GLTFLoader().setPath(gltfpath );
            loader.load( gltfurl, function ( gltf ) {
                //console.log(gltf.scene)
                gltfobj=gltf
                // //console.log(JSON.stringify(gltf.scene))

                // //console.log(gltf)
                let c = 0
                gltf.scene.traverse( function ( child ) {

                    // if(child.isGroup){
                    //     //console.log("groupppppppppppppppppppppppppppppp")
                    //     //console.log(child)
                    //     c=c+1
                    // }
                    if(child.isCamera){
                        //console.log("groupppppppppppppppppppppppppppppp")
                        //console.log(child)
                        c=c+1
                    }


                    for(let mm in newjsondata){
                        //console.log("UniqueId")
                        //console.log(child.userData.UniqueId)
                        //console.log(child)

                        if(newjsondata[mm].indexOf(child.userData.UniqueId)!=-1){

                            // //console.log(newjsondata[mm])
                            // //console.log(mm)
                            // //console.log(child.userData.UniqueId)
                            if(child.userData.UniqueId!=undefined){
                                if(objectMESH[mm]){
                                    objectMESH[mm].push(child)
                                }else{
                                    objectMESH[mm]=[]
                                    objectMESH[mm].push(child)
                                }
                            }

                        }else{
                            // if(child.userData.Properties){
                            //         if(objectMESH[mm]){
                            //             objectMESH[mm].push(child)
                            //         }else{
                            //             objectMESH[mm]=[]
                            //             objectMESH[mm].push(child)
                            //         }
                            //     }else{
                            //         //console.log(child)
                            //         if(objectMESH["unknow"]){
                            //             objectMESH["unknow"].push(child)
                            //         }else{
                            //             objectMESH["unknow"]=[]
                            //             objectMESH["unknow"].push(child)
                            //         }
                            //  }
                        }
                    }


                    if(child.userData.name){
                        // child.geometry.dispose(); // 删除几何体
                        // child.material.dispose(); // 删除材质
                        //console.log("查看mesh")
                        if(child.userData.Properties){

                        }else{
                            //console.log(child)
                            if(objectMESH["unknow"]){
                                objectMESH["unknow"].push(child)
                            }else{
                                objectMESH["unknow"]=[]
                                objectMESH["unknow"].push(child)
                            }
                        }

                    }else{
                        if(objectMESH["unknow"]){
                            objectMESH["unknow"].push(child)
                        }else{
                            objectMESH["unknow"]=[]
                            objectMESH["unknow"].push(child)
                        }
                    }
                    if ( child.isMesh ) {
                        // child.material.transparent=true
                        if(child.material.name=="玻璃"){
                            // //console.log("玻璃玻璃玻璃玻璃玻璃玻璃玻璃玻璃玻璃玻璃玻璃玻璃")
                            // //console.log(child.material.name)
                            child.material.transparent=true
                        }

                        // child.material.depthWrite=false
                        // //console.log(   child.material)
                        // child.material.opacity=0.9
                        // 、、  child.material.emissive =  child.material.color;
                       // child.material.emissiveMap = child.material.map ;
                        child.castShadow = true;
                        child.receiveShadow = true;
                    }else{
                        //console.log("uuuuuuuuuuuuiiiiiiiiiiiiiiiiddddddddd")
                        //console.log(child)
                    }

                } );
                //console.log("总共ddddddddddd"+c)
                //console.log(objectMESH)

                if(objectMESH){
                    $.dialog({id:'testID2x'}).close();
                    //console.log("xxxxxxxxxx1111111111122222222"+c)
                   // let nxobjectMESH=JSON.stringify(objectMESH)
                    let objectMESHx= objectMESH
                    let hm =

                        "<div class='tableTop abs'><div>"
                    for (let  z in objectMESH){


                        hm+="    <div class='table border'>\n" +
                            "        <div class='text-right dleft border'>"+z+":&nbsp;&nbsp;&nbsp;&nbsp;<span id='doshowx'  key='"+z+"'  >显示</span>  <span   key='"+z+"'  id='dohidex'>隐藏</span> </div>\n" +
                            "    </div>\n"

                    }
                    hm+="</div></div>"+"<script>\n"
                    $("body").append(hm)

                    $("body").on("click","#doshowx",function(){
                        let key =$(this).attr("key")
                        if(objectMESH[key]){
                            // 显示对应楼层的  工人
                            for(let ms in mengroupLevel[key]){
                                mengroupLevel[key][ms].visible = true
                            }
                            // 显示对应楼层的  摄像头
                            for(let ms in cameragroupLevel[key]){
                                cameragroupLevel[key][ms].visible = true
                            }
                            // 显示对应楼层的信标
                            for(let ms in xinbiaoGroupLevel[key]){
                                xinbiaoGroupLevel[key][ms].visible = true
                            }


                            scene.traverse( function ( childs ) {

                                if(childs.isGroup) {

                                    childs.traverse( function ( child ) {

                                        if(child.isMesh){
                                            for (let q in objectMESH[key]) {
                                                if (objectMESH[key][q].name == child.name) {
                                                    // //console.log(child.name)
                                                    // //console.log(child)
                                                    // child.material.visible=false
                                                    objectMESH[key][q].visible = true


                                                }
                                            }
                                        }

                                    })


                                }
                            })

                            render()
                        }


                        //这里做你的操作
                    })

                    $("body").on("click","#dohidex",function(){
                        let key =$(this).attr("key")
                        //console.log("点击隐藏")
                        //console.log(key)
                        //console.log(objectMESH[key])

                        if(objectMESH[key]){
                            //console.log(objectMESH[key])
                            //console.log(123123)


                            // 隐藏对应楼层的  工人
                            for(let ms in mengroupLevel[key]){

                                mengroupLevel[key][ms].visible = false

                            }

                            //  隐藏对应楼层的  摄像头
                            for(let ms in cameragroupLevel[key]){
                                cameragroupLevel[key][ms].visible = false
                            }
                            //  隐藏对应楼层的信标
                            for(let ms in xinbiaoGroupLevel[key]){
                                xinbiaoGroupLevel[key][ms].visible = false
                            }


                            scene.traverse( function ( childs ) {

                                if(childs.isGroup) {

                                    childs.traverse( function ( child ) {

                                        if(child.isMesh){
                                            for (let q in objectMESH[key]) {
                                                if (objectMESH[key][q].name == child.name) {
                                                    // //console.log(child.name)
                                                    // //console.log(child)
                                                    // child.material.visible=false
                                                    // msg("keyyyyyyyyyyyyy")
                                                    // msg(key)
                                                    // msg(q)
                                                    // msg(mengroupLevel)
                                                    objectMESH[key][q].visible = false


                                                }
                                            }
                                        }



                                    })


                                }
                            })
                            // scene.children[4].traverse( function ( child ) {
                            //     if(child.isMesh){
                            //         for(let q in objectMESH[key]){
                            //             if(objectMESH[key][q].name==child.name){
                            //                 // //console.log(child.name)
                            //                 // //console.log(child)
                            //                 // child.material.visible=false
                            //                 objectMESH[key][q].visible=false
                            //
                            //             }
                            //         }
                            //
                            //     }
                            //
                            //
                            // })

                            render()
                        }


                        //这里做你的操作
                    })


                    // $.dialog({
                    //     top:"0px",
                    //     title: "菜单目录",
                    //     width:"100%",
                    //     id: 'testID2x',
                    //     content: hm,
                    //
                    // });


                }

                doSetCameraPosition(gltf)

                const loaderx = new THREE.FontLoader();;
                loaderx.load( 'threejs/fonts/gentilis_regular.typeface.json', async function ( font ) {

                    //console.log("modelSize")
                    //console.log(modelSize)
                    //console.log(centetposition)
                    //console.log( gltf.scene.position)
                    // 加字体
                    function addLabel( name, location ) {

                        const textGeo = new THREE.TextBufferGeometry( name, {
                            font: font,
                            size: modelSize/20,
                            height: 1,
                            curveSegments: 1

                        } );
                        const textMaterial = new THREE.MeshBasicMaterial( { color: 0xffffff } );
                        const textMesh = new THREE.Mesh( textGeo, textMaterial );

                        textMesh.position.copy( location );
                        textMesh.vertexColors

                        // scene.overrideMaterial= new THREE.MeshLambertMaterial({color:0xffffff})
                        scene.add( textMesh );
                        render()
                    }


                    function pianyi(type="x"){
                        switch (type){
                            case "x":


                                break;
                            case "y":


                                break;
                            case "z":


                                break;

                        }


                    }

                    let cps = centetposition.clone()
                    let cps1 = centetposition.clone()
                    let cps2 = centetposition.clone()
                    let cps3 = centetposition.clone()

                    cps.x += (gltf.scene.position.x - centetposition.x);
                    cps.y += (gltf.scene.position.y - centetposition.y);
                    cps.z += (gltf.scene.position.z - centetposition.z);
                    cps.y -=modelSize/5;
                    cps.x +=modelSize/5;
                    //console.log(gltf.scene.position.x )
                    //console.log(centetposition.x)
                    await addLabel( "X:"+modelX, cps );

                    cps1.x += (gltf.scene.position.x - centetposition.x);
                    cps1.y += (gltf.scene.position.y - centetposition.y);
                    cps1.z += (gltf.scene.position.z - centetposition.z);
                    cps1.z -= modelSize/2;
                    cps1.x -=modelSize/3
                    await addLabel(  "Y:"+modelY, cps1 );


                    cps2.x += (gltf.scene.position.x - centetposition.x);
                    cps2.y += (gltf.scene.position.y - centetposition.y);
                    cps2.z += (gltf.scene.position.z - centetposition.z);
                    cps2.z -= modelSize/2;
                    cps2.x +=modelSize
                    await addLabel(  "Z:"+modelZ, cps2 );



                } );
            } );






        }catch (e) {
            //console.log("异常错误")
            //console.log(e)
            $.dialog({id:'loading'}).close();

        }
    }



    let textGroup =[]
    // 根据模型位置设置  摄像头位置
    function doSetCameraPosition(gltf){
        // 重置镜头旋转
        // controls.reset();

        const box = new THREE.Box3().setFromObject(gltf.scene);
        const size = box.getSize(new THREE.Vector3()).length();
        const center = box.getCenter(new THREE.Vector3());




        //
        //
        // //console.log("sizeeeeeeeeeeeeeeeee")
        // //console.log(box)
        // //console.log(size)
        modelBox = box

        centetposition = center
        modelSize = size
        dogrid()

        //  //console.log("size===============")
       //  //console.log(gltf)
       //  //console.log(size)
       //  //console.log(center)
       // let geometryx = new THREE.BoxGeometry(center.x+size/2, center.y+size/2, center.z+size/2); //宽，高，深
       //  let material = new THREE.MeshBasicMaterial({
       //      color: "#f60",
       //      wireframe: true
       //  }); //wireframe默认为false
       //  let cube = new THREE.Mesh(geometryx, material);
       //  scene.add(cube);


        modelX = box.max.x-box.min.x
        modelY = box.max.y-box.min.y
        modelZ = box.max.z-box.min.z

        //
        //
        // const cp = new THREE.BufferGeometry();
        // cp.setFromObject(gltf.scene)
        // // // // 单构件加外边框   包围盒  start
        // // // let mqs = gltf.scene.clone()
        // // // // mqs.rotation.x+=4.7
        // // // let cp = mqs.geometry
        // let taup = 900
        // //
        // //console.log(cp.boundingBox)
        //  //console.log("xxxxxxxxxxxxxxxxxxxxx")
        //  //console.log("xxxxxxxxxxxxxxxxxxxxx")
        //
        // var object = new THREE.Mesh(cp, new THREE.MeshBasicMaterial(0xff0000));
        // let   boxx= new THREE.BoxHelper(object, 0xffff00);
        // scene.add(boxx);
        // // 单构件加外边框   包围盒  end
        // // 旋转重置


        let cc =new THREE.Vector3()
        //
        // let location =   center.clone()
        //
        // let location2 = center.clone()
        // let location3 =  center.clone()
        // //


        gltf.scene.position.x += (gltf.scene.position.x - center.x);
        gltf.scene.position.y += (gltf.scene.position.y - center.y);
        gltf.scene.position.z += (gltf.scene.position.z - center.z);


        controls.maxDistance = size * 10    ;
        camera.near = size / 100;
        camera.far = size * 100;

        camera.position.copy(center);
        camera.position.x += size/2.0;
        camera.position.y +=  size/5.0;
        camera.position.z +=  size/2.0;
        camera.lookAt(center);
        camera.updateProjectionMatrix();
        firstCont = new THREE.Vector3(center.x,center.y,center.z)
        firstContpostion = new THREE.Vector3( camera.position.x, camera.position.y, camera.position.z)
        // //console.log(camera.position)

        //
        // camera.position.x += size;
        // camera.position.y += size;
        // camera.position.z += size;
        // //console.log("cccccccccccc")
        // //console.log(center)
        //
        // //console.log("cccccccccccc22222222")


        gltf.scene.rotation.x=4.7
        controls.update()
        // gltf.scene.position.y+=modelBox.max.y-modelBox.min.y
        // gltf.scene.position.x+=modelBox.max.x-modelBox.min.x
        scene.add(gltf.scene );
        camera.rotateX(0.001)

        $.dialog({id:'loading'}).close();

        const geometry = new THREE.BoxBufferGeometry(modelX, modelY, modelZ);
        const edges = new THREE.EdgesGeometry( geometry );
        const line = new THREE.Mesh( edges, new THREE.MeshBasicMaterial( { color: 0xffffff } ) );
        line.rotation.x+=4.7

        line.position.y += (gltf.scene.position.y - center.y)/2;
        line.position.z -=size-size/2;
       let  xase3=  new THREE.BoxHelper( line )
        // scene.add( xase3 );



        // let
        // xase3.rotation.x+=4.7
        //
        //
        // //console.log("line.position")
        // //console.log(xase3.position)
        // scene.add(xase3 );
        // let  edgesx = new THREE.EdgesHelper( meshx, 0x00ff00 );




        let location = gltf.scene.position.clone()

        let location2 =gltf.scene.position.clone()
        let location3 = gltf.scene.position.clone()



        modelX = box.max.x-box.min.x
        modelY = box.max.y-box.min.y
        modelZ = box.max.z-box.min.z

        location.z = (box.max.z-box.min.z)/2
        location.x += (box.max.x-box.min.x)/2
        location.y-= 800

        dotxt("X:"+modelX+"mm ",location);


        location2.y+= (box.max.y-box.min.y)/2
        dotxt("y:"+modelY+"mm",location2);



        location3.z+=(box.max.z-box.min.z)/2
        location3.x=(box.max.x-box.min.x)/2
        location3.y=(box.max.y-box.min.y)/2
        dotxt("z:"+Math.round(modelZ)+"mm",location3);
        dodiban()

        doAxsHelper()

        dobujian(gltf)
        // 标注
        function dotxt(str,location,type="x"){
            const earthDiv = document.createElement( 'div' );
            earthDiv.className = 'label';
            earthDiv.textContent = str;

            // //console.log("eeeeeeeeeeeeeemmmmmmmmmmmmm")
            // //console.log(modelSize/200)
            earthDiv.style.fontSize =modelSize/33+'pt';

            earthDiv.style.color = '#f60';
            const earthLabel = new CSS3DObject( earthDiv );
         //   earthLabel.position .copy(location)
          //  earthLabel.position .copy(location)
          //   //console.log(333333333)
            const geometryx = new THREE.PlaneGeometry( 0, 0,  0 );
            const materialx = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
            const meshx = new THREE.Mesh( geometryx, materialx );
            meshx.position .copy(location)
            meshx.rotation.x+=4.7
            meshx.add( earthLabel );




            // meshx.position.x+=meshx.position.x- centetposition.x
            // meshx.position.y+=meshx.position.y- centetposition.y
            // meshx.position.z+=meshx.position.z- centetposition.z


            // scene.add( ma2 );
            // meshx.add(earthLabel)

            // meshx.rotation.y-=Math.PI/2
            // meshx.rotation.x-=Math.PI/2
            // meshx.position.z+=modelSize/5
            // //console.log("xxxxxxxxxxxxxxxx")
            // //console.log(earthLabel)
            // //console.log(location)
             // scene.add( meshx );
              textGroup.push(meshx)

            if(type=="z"){

                meshx.rotation.z+=3.14/2
            }

            if(type=="y"){

                meshx.rotation.z+=3.14/2
            }
            scene.add( meshx );
            controls.addEventListener( 'change', changexxx ); // use if there is no animation loop
        }



        render()

    }




    function showx(key){
        if(objectMESH[key]){
            for(let q in objectMESH[key]){
                objectMESH[key][q].visible=true
            }
        }
    }

    function hidex(key){
        if(objectMESH[key]){
            for(let q in objectMESH[key]){
                objectMESH[key][q].visible=false
            }
        }
    }
    function  dogrid(){

       msg("modelsize=============")
       msg(modelSize)

        let  gridHelper=new THREE.GridHelper(modelSize*2,modelSize/1000,"#fefefe","#fefefe");
        // console.log("this.gltfModelCenterPosition")
        // console.log(this.gltfModelCenterPosition)
        gridHelper.position.x=modelBox.x;
        gridHelper.position.y-=modelBox.y;
        gridHelper.position.z+=modelBox.z;
        //
        // gridHelper.rotation.x =this.rotation
        scene.add(gridHelper);
        msg("modelsize=============")

    }

    function onWindowResize() {



        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize( window.innerWidth, window.innerHeight );


        render();
    }


    var projector =new THREE.Raycaster()
    function onDocumentMouseDown(event){
        // // scene.remove(scene.children[0])
        // //console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxasdasd")
        // //console.log(gltfobj)
        // for (let i of scene.children){
        //     //console.log(i)
        //     // scene.remove(i)
        //     // i.remove(i)
        //     // scene.children.remove()
        //
        // }
        // render();
        return
        let objectss =[]
        let mouse = new THREE.Vector2();
        //console.log(scene)
        //将鼠标点击位置的屏幕坐标转成threejs中的标准坐标,具体解释见代码释义
        let x = (event.clientX / window.innerWidth) * 2 - 1;
        let y = -(event.clientY / window.innerHeight) * 2 + 1;
        //新建一个三维单位向量 假设z方向就是0.5
        //根据照相机，把这个向量转换到视点坐标系
        var vector = new THREE.Vector3(x, y,0.5).unproject(camera);

        //在视点坐标系中形成射线,射线的起点向量是照相机， 射线的方向向量是照相机到点击的点，这个向量应该归一标准化。
        var raycaster = new THREE.Raycaster(mouse, camera);


        scene.group.forEach(child=>{
            //console.log(child)
            if(child in THREE.Mesh){
                objectss.push(child)
            }
        })

        //射线和模型求交，选中一系列直线
        var intersects = raycaster.intersectObjects( objectss);
        //console.log('imtersrcts=' + intersects)
        if (intersects.length > 0) {
            //选中第一个射线相交的物体
            let  SELECTED = intersects[0].object;
            var intersected = intersects[0].object;
            //console.log(intersects[0].object)
        }
    }


    function createShaderMaterial( shader) {

        const u = THREE.UniformsUtils.clone( shader.uniforms );

        const vs = shader.vertexShader;
        const fs = shader.fragmentShader;

        const material = new THREE.ShaderMaterial( { uniforms: u, vertexShader: vs, fragmentShader: fs } );


        return material;

    }
    function guanghui(){

        let composer = new EffectComposer(renderer)
        let renderPass = new RenderPass(scene, camera);
        composer.addPass(renderPass);

        let outlinePass = new OutlinePass(new THREE.Vector2(window.innerWidth, window.innerHeight), scene, camera);
        composer.addPass(outlinePass);

        outlinePass.visibleEdgeColor.set('#130AF2'); // 选中颜色
        outlinePass.edgeStrength = 5;
        outlinePass.edgeGlow = 1.5;
        const render = function () {
            //console.log(333333333333333)

            composer.render();
        }


    }


    function dodiban(){

        // let floorGeometry = new PlaneGeometry(modelSize*2, modelSize*2,modelSize*2);
        // let floorMaterial = new MeshPhongMaterial({
        //     color: 0xffffff,
        //     //   color:  colorArr[colorIndex],
        //     shininess: 0,
        //     // wireframe: true
        // });
        // floor = new Mesh(floorGeometry, floorMaterial);
        // //console.log(22123123123)
        // //console.log(centetposition)
        // floor.position.copy(centetposition)
        // //   floor.position.y = -2.1;
        // floor.rotation.x +=4.7  // -0.5 * Math.PI;
        // floor.position.y -=modelSize/2  // -0.5 * Math.PI;
        //
        // // 地板接受阴影开启
        // floor.receiveShadow = true;
        // scene.add(floor);

        // var gridHelper = new THREE.GridHelper( modelSize*2, modelSize*2, 0x2C2C2C, 0x888888 );
        // gridHelper.position.copy(centetposition)
        // gridHelper.position.y -=modelSize/6  // -0.5 * Math.PI;
        // scene.add(gridHelper);


        //
        // let floorGeometry = new PlaneGeometry(1000, 1000, 1);
        // let floorMaterial = new MeshPhongMaterial({
        //     color: 0x77F28F,
        //     //   color:  colorArr[colorIndex],
        //     shininess: 0,
        //     // wireframe: true
        // });
        // floor = new Mesh(floorGeometry, floorMaterial);
        // floor.rotation.x = -0.5 * Math.PI;
        // floor.position.y = -2.1;
        //
        // // 地板接受阴影开启
        // floor.receiveShadow = true;
        // scene.add(floor);
    }

    let cameragroup =[]
    let mengroup =[]
    let xinbiaoGroup =[]

    let cameragroupLevel ={}
    let mengroupLevel ={}
    let xinbiaoGroupLevel ={}



    // 点击部件
    function  dobujian(gltf){



       // let ge = new THREE.BoxGeometry(200,100,300)
       // let me =  new THREE.MeshBasicMaterial(0xff0000)
       //
       //
       // let  object = new THREE.Mesh(ge, me);
       //
       //
       // scene.add(object)

        //console.log("点击部件")
        let raycaster = new THREE.Raycaster();
        let mouse = new THREE.Vector2();
        const selectHandler = function (ev) {

            if(ev.clientX==undefined){
                ev.clientX =ev.originalEvent.changedTouches[0].clientX
            }
            if(ev.clientY==undefined){
                ev.clientY =ev.originalEvent.changedTouches[0].clientY
            }
            // mouse.x = (ev.clientX / window.innerWidth) ;
            // mouse.y = -(ev.clientY / window.innerHeight);

            mouse.x = (ev.clientX / window.innerWidth) * 2 - 1;
            mouse.y = -(ev.clientY / window.innerHeight) * 2 + 1;
            raycaster.setFromCamera(mouse, camera);
            // 这里我们只检测模型的选中情况
            let intersects = raycaster.intersectObjects(gltf.scene.children, true);


            let intersectsx = raycaster.intersectObjects(cameragroup, true);


            if (intersects.length > 0) {

                let doobj ;
                for(let i =0;i<intersects.length;i++){
                    if (intersects[i].object.visible) {
                        msg("当前对象是"+i)
                        doobj = intersects[i];
                        break
                    }
                }

                // 所在楼层
                let  dolouceng ;
                for(let level in newjsondata){
                    if(newjsondata[level].indexOf(doobj.object.userData.UniqueId)!=-1) {
                        dolouceng =level;
                    }
                }

                //console.log(intersects)
                // 加摄像头
                if(docameraAdd){

                    let dosize = modelSize/30
                    // 添加平面几何体
                    let  geometryss = new THREE.PlaneBufferGeometry(dosize, dosize,dosize);

                    let materialss = new THREE.MeshBasicMaterial({map:cubeTexture});
                    let Mesh = new THREE.Mesh(geometryss,materialss)

                    Mesh.position.x=doobj.point.x-dosize/4
                    Mesh.position.y=doobj.point.y+dosize/2
                    Mesh.position.z=doobj.point.z-dosize/2
                    Mesh.material.transparent = true;
                    cameragroup.push(Mesh)

                    if( cameragroupLevel[dolouceng]){
                        cameragroupLevel[dolouceng].push(Mesh)

                    }else{
                        cameragroupLevel[dolouceng]=[]
                        cameragroupLevel[dolouceng].push(Mesh)
                    }
                    scene.add(Mesh)
                    scene.rotation.x+=0.00001
                    controls.update()
                }


                // 加人
                if(addMenAdd){
                    msg("增加人")
                    // 查看当前是那个显示的元素
                    // 查找到显示中的对象
                    msg(objectMESH)
                    msg(newjsondata['2F'])


                    // 楼层小人  所属楼层
                    msg(doobj)




                    console.log(doobj.point)
                    let  nowV = new THREE.Vector3(doobj.point)

                    let dosize = modelSize/30
                    // 添加平面几何体
                    let  geometryss = new THREE.PlaneBufferGeometry(dosize, dosize,dosize);
                    let materialss = new THREE.MeshBasicMaterial({map:cubeTextureMen});
                    let Mesh = new THREE.Mesh(geometryss,materialss)
                    Mesh.position.x=doobj.point.x-dosize/4
                    Mesh.position.y=doobj.point.y+dosize/2
                    Mesh.position.z=doobj.point.z-dosize/2
                    Mesh.material.transparent = true;
                    Mesh.rotateX(0.001)
                    console.log(Mesh.position)


                    mengroup.push(Mesh)
                    if( mengroupLevel[dolouceng]){
                        mengroupLevel[dolouceng].push(Mesh)

                    }else{
                        mengroupLevel[dolouceng]=[]
                        mengroupLevel[dolouceng].push(Mesh)
                    }
                    scene.add(Mesh)
                    controls.update()
                }



                // 增加信标
                if(xinbiaoAdd){
                    console.log("didddddddddddddddddddddd2222222222222d")

                    let m = flagObj.scene.clone()

                    // 获取信标大小
                    const box = new THREE.Box3().setFromObject(m);
                    const size = box.getSize(new THREE.Vector3()).length();
                    const center = box.getCenter(new THREE.Vector3());
                    let dosize = modelSize/30
                    let sss = size/modelSize/20
                    m.position.x=doobj.point.x
                    m.position.y=doobj.point.y
                    m.position.z=doobj.point.z
                    m.rotation.x+=4.7
                    m .scale.set(sss,sss,sss)
                    if( xinbiaoGroupLevel[dolouceng]){
                        xinbiaoGroupLevel[dolouceng].push(m )

                    }else{
                        xinbiaoGroupLevel[dolouceng]=[]
                        xinbiaoGroupLevel[dolouceng].push(m )
                    }
                    scene.add(m )

                }

                // changecolor(intersects[0].object)
                //  selectedObjects.layers,toggle(1)
                //
                for ( let i = 0; i < intersects.length; i ++ ) {
                    if (intersects[i].object.visible) {
                        let selectedObjects = intersects[i].object;
                        changecolor(selectedObjects)
                        break
                     }
                   // intersects[ i ].object.material.color.set( 0xff0000 );
                }
            }
        }


        if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i))) {
            //console.log("手机访问111111111.");
            $(document).on('click touchend',function(e){
                selectHandler(e)
                //console.log("2222222222xxxxxxxxxxx")
                //  location.href = $(this).attr('data-url');
                //  return false;
            });
        }else{
            document.body.addEventListener('click', selectHandler, false);

            //console.log("电脑访问111111111.");
        }



        //  document.body.addEventListener('click', selectHandler, false);
    }


    function resizeSelectHandle(){

    }

    function addSelectedObject( object ) {

        selectedObjects = [];
        selectedObjects.push( object );

    }


    function initObject (x,y,z) {
        let  geometry = new THREE.Geometry();
        //console.log(scene.position)
        //console.log(camera.position)
        geometry.vertices.push(
            new THREE.Vector3(camera.position.x-100, camera.position.y, camera.position.z-100),
            new THREE.Vector3(camera.position.x-100, camera.position.y-10, camera.position.z),


            new THREE.Vector3(camera.position.x, camera.position.y, camera.position.z-200),
            new THREE.Vector3(camera.position.x, camera.position.y-20, camera.position.z-200),
            new THREE.Vector3(camera.position.x, camera.position.y-30, camera.position.z-200),
        );
        geometry.colors.push(
            new THREE.Color(0x444444),
            new THREE.Color(0xFF0000)
        )
        let  material = new THREE.LineBasicMaterial({vertexColors: true});
        var line = new THREE.Line(geometry, material);
        scene.add(line);
    }


   function changecolor(selectedObjects){

       // selectedObjects.visible=false
       console.log("选中、、、、、、、、、、、、、、")
       //console.log(scene)
       //console.log(scene.children[3])
        let newMaterial = selectedObjects.material.clone();
        let oldMaterialObj  = selectedObjects.material.clone();
        const box = new THREE.Box3().setFromObject(selectedObjects);
        const size = box.getSize(new THREE.Vector3()).length();
        const center = box.getCenter(new THREE.Vector3());
        console.log(selectedObjects.geometry)
       var selectedObject =  scene.getObjectByName(selectedObjects.name);
       //console.log("xxxxxxxxxxxxxxxxxxxx")
       //console.log(selectedObject)
        //console.log("twenennnnnnnnnnnnnnnnn")
        //console.log(cameraPosition)
        //console.log(center)
       let move =  new  THREE.Vector3( camera.position.x, camera.position.y, camera.position.z)
       //console.log(move)

        // try{
        //     var p1 =camera.position.clone();
        //
        //     var tweena = cameraCon({x:p1.x+11200,y:p1.x+12000},3000);
        //     // var tweenb = cameraCon({x:0,y:10,z:-20},9000);
        //     // var tweenc = cameraCon({x:-20,y:2,z:0},4000);
        //     // var tweend = cameraCon({x:0,y:10,z:20},4000);
        //     // tweena.chain(tweenb);
        //     // tweenb.chain(tweenc);
        //     // tweenc.chain(tweend);
        //     // tweend.chain(tweena);
        //     tweena.start();
        //
        //     function cameraCon(p2={x:10,y:30,z:10},time=6000) {
        //         //console.log(1123123123)
        //
        //
        //         var tween1 = new TWEEN.Tween(p1).to(p2,time).easing(TWEEN.Easing.Quadratic.InOut);
        //         var upxdate = function () {
        //
        //             camera.lookAt(center);
        //         };
        //         tween1.onUpdate(upxdate);
        //         return tween1;
        //     }
        //
        //
        //
        // }catch (e){
        //     //console.log(e)
        // }

       // camera.lookAt(center);
       //
       //
       //
       // new TWEEN.Tween({x:0,y:400})
       //     .to( { x : 400, y: 50 }, 5000 )
       //     .easing(TWEEN.Easing.Linear.None)
       //     // .onUpdate(function(){
       //     //
       //     //     render()
       //     // }  )
       //     .start();

        // camera.lookAt(center)

        let    sphere = new THREE.SphereGeometry(3.5);

        //console.log("33333333333111111111333333331")
        //console.log(size2)


        // // 单构件加外边框   包围盒  start
        // let mqs = selectedObjects.clone()
        // // mqs.rotation.x+=4.7
        // let cp = mqs.geometry
        // let taup = 900
        // cp.boundingBox.min.x=cp.boundingBox.min.x-taup
        // cp.boundingBox.min.y=cp.boundingBox.min.y-taup
        // cp.boundingBox.min.z=cp.boundingBox.min.z-taup
        // cp.boundingBox.max.x=cp.boundingBox.max.x+taup
        // cp.boundingBox.max.y=cp.boundingBox.max.y+taup
        // cp.boundingBox.max.z=cp.boundingBox.max.z+taup
        // //console.log(cp)
        // var object = new THREE.Mesh(cp, new THREE.MeshBasicMaterial(0xff0000));
        // let   boxx= new THREE.BoxHelper(object, 0xffff00);
        // scene.add(boxx);
        // // 单构件加外边框   包围盒  end

        //console.log("objectName")
        //console.log("box")
        //console.log(box)
        //console.log("size")
        //console.log(size)
        //console.log("center")
        //console.log(center)

        let v = new THREE.Vector3()
        // //console.log(selectedObjects.position)
        //
        // // 创建动画
        // // let component = gltf.scene.getObjectByName('car_body');
        // TweenLite.to(selectedObjects.position,5, {
        //     y: 50,
        //     x:500,
        //     ease: Bounce.easeOut
        // });


        let selectedObjectsx = [];


        let color = newMaterial.color
        if(oldSelect && oldMaterial){
            if(oldSelect.uuid == selectedObjects.uuid){
                newMaterial = oldMaterial
                //     newMaterial.color
                oldMaterial = ''
                oldSelect = ''
                outlinePass.selectedObjects = []
                $.dialog({id:'testID2'}).close();
                render()
                return
            }else{
                oldSelect.material = oldMaterial
                oldMaterial = ''
                oldSelect = ''
                oldSelect =  selectedObjects
                oldMaterial = oldMaterialObj
                selectedObjectsx.push( selectedObjects );
                outlinePass.selectedObjects = selectedObjectsx
                newMaterial.color =  new THREE.Color(colorArr[colorIndex]); //重新修改颜色
            }

        }else{
            oldSelect =  selectedObjects
            oldMaterial = oldMaterialObj
            selectedObjectsx.push( selectedObjects );
            outlinePass.selectedObjects = selectedObjectsx
            newMaterial.color =  new THREE.Color(colorArr[colorIndex]); //重新修改颜色
        }

        let  uuidKey = selectedObjects.userData.UniqueId

        //console.log(selectedObjects)



        let attart = selectedObjects.userData.Properties


        let html = "<div class='tableTop'>\n"


        html+="    <div class='table border'>\n" +
            "        <div class='text-right dleft border'>name:</div>\n" +
            "        <div class='text-left dright'>"+selectedObjects.name+"</div>\n" +
            "    </div>\n"
        //
        // html+="    <div class='table border'>\n" +
        //     "        <div class='text-right dleft border'>uuid:</div>\n" +
        //     "        <div class='text-left dright'>"+selectedObjects.uuid+"</div>\n" +
        //     "    </div>\n"

        if(jsondata[uuidKey]){

            let danwei = "M"
            let rows = jsondata[uuidKey]
            //
            // html+="    <div class='table border'>\n" +
            //     "        <div class='text-right dleft border'>项目名称:</div>\n" +
            //     "        <div class='text-left dright'>"+rows.ProjectName+"</div>\n" +
            //     "    </div>\n"

            html+="    <div class='table border'>\n" +
                "        <div class='text-right dleft border'>类型:</div>\n" +
                "        <div class='text-left dright'>"+rows.Type+"</div>\n" +
                "    </div>\n"


            html+="    <div class='table border'>\n" +
                "        <div class='text-right dleft border'>长:</div>\n" +
                "        <div class='text-left dright'>"+rows.Length+danwei+"</div>\n" +
                "    </div>\n"


            html+="    <div class='table border'>\n" +
                "        <div class='text-right dleft border'>宽:</div>\n" +
                "        <div class='text-left dright'>"+rows.Width+danwei+"</div>\n" +
                "    </div>\n"


            html+="    <div class='table border'>\n" +
                "        <div class='text-right dleft border'>厚/高:</div>\n" +
                "        <div class='text-left dright'>"+rows.Height+danwei+"</div>\n" +
                "    </div>\n"





        }
       if(attart){
           for( let i in attart ){
               html+="    <div class='table border'>\n" +
                   "        <div class='text-right dleft border'>"+i+":</div>\n" +
                   "        <div class='text-left dright'>"+attart[i]+"</div>\n" +
                   "    </div>\n"
           }


       }

        html+="</div>"
        $.dialog({id:'testID2'}).close();



        let winW = window.innerWidth
       if(winW<=414){

           $.dialog({
               top:"100%",
               left:"100%",
               title: "构件信息",
               width:"100%",
               id: 'testID2',
               content: html
           });
       }else{

           $.dialog({
               top:"0%",
               left:"100%",
               title: "构件信息",
               width:"100%",
               id: 'testID2',
               content: html
           });
       }

       // selectedObjects.material = newMaterial;
        render()
    }

    function msg(msg){
       console.log(msg);

    }
    createGUI()
    // 创建ui界面
    function createGUI() {
        return

        if ( gui ) gui.destroy();

        gui = new GUI( { width: 400 } );

        // SHADOW


        let  guiData={
            drawStrokes:true,
            drawFillShapes:4,
            strokesWireframe:true,
            fillShapesWireframe:true,
        }



        gui = new GUI( { width: 350 } );
        gui.addFolder( "Shadow" );

        gui.add( guiData, 'drawStrokes' ).name( 'Draw strokes' ).onChange( update );

        gui.add( guiData, 'drawFillShapes',1,100 ).name( 'Draw fill shapes' ).onChange( update );

        gui.add( guiData, 'strokesWireframe' ).name( 'Wireframe strokes' ).onChange( update );

        gui.add( guiData, 'fillShapesWireframe' ).name( 'Wireframe fill shapes' ).onChange( update );


        function update() {

        }

    }


    //清理效果
    function cleaningEffect(){


    }


    //内存  帧数 仪表
    function dostats(){
        stats = new Stats();
        $("#stat").html( stats.dom)

    }

    function changexxx(){
       //console.log("changexxxchangexxxchangexxxchangexxxchangexxxchangexxxchangexxx")
        for (let i=0;i<textGroup.length;i++){
            textGroup[i].rotation.copy(camera.rotation)
            // planeGroup[i].rotation.copy(camera.rotation)
        }

        for (let i=0;i<cameragroup.length;i++){
            cameragroup[i].rotation.copy(camera.rotation)
            // planeGroup[i].rotation.copy(camera.rotation)
        }
        for (let i=0;i<xinbiaoGroup.length;i++){
            xinbiaoGroup[i].rotation.copy(camera.rotation)
            // planeGroup[i].rotation.copy(camera.rotation)
        }


        for (let i=0;i<mengroup.length;i++){
            mengroup[i].rotation.copy(camera.rotation)
            // planeGroup[i].rotation.copy(camera.rotation)
        }

    }

    function render() {
        if(labelRenderer){
            // labelRenderer.render( scene, camera );
        }

        // requestAnimationFrame(render)
        composerAll.render()
        stats.update()

        // shadowCameraHelper.update();
    }



</script>



<script>
    $(function(){
        let h  =$(window).height()
        $(".box").height(h)
        $(".left a ").eq(1).addClass("hover")
        $(".left a ").click(function(){
            $(".left a ").removeClass("hover")
            $(this).addClass("hover")

        })
    })

</script>
<style>
    .tableTop{
        max-height: 300px;
        overflow-y: scroll;
        min-width: 100px;
        border:1px solid red;
        background: #fff;
    }
    .abs{
        position: fixed;
        top: 50px;
        left: 0px;
    }
    .label {
        /*margin-top: -20px;*/
        color: #fff;
        padding: 3px 5px;
        background:#FFF1B8
    }
</style>
</body>
</html>
